package org.mspring.mlog.web.freemarker.directive;

import java.io.IOException;
import java.util.Map;

import org.mspring.mlog.core.ServiceFactory;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.utils.WebUtils;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.freemarker.DirectiveUtils;
import org.mspring.platform.web.freemarker.directive.AbstractDirectiveModel;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 
 * @author Gao Youbo
 * @since 2013年7月9日
 */
public class PostUrlDirectiveModel extends AbstractDirectiveModel {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public void exec(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        // TODO Auto-generated method stub
        Long id = DirectiveUtils.getLong("id", params); // 文章编号
        if (id == null) {
            env.getOut().append("#");
            return;
        }
        String username = DirectiveUtils.getString("username", params);
        if (StringUtils.isBlank(username)) {
            Long userid = DirectiveUtils.getLong("userid", params);
            if (userid == null) {
                env.getOut().append("#");
                return;
            }
            User user = ServiceFactory.getUserService().get(userid);
            if (user == null) {
                env.getOut().append("#");
                return;
            }
            username = user.getName();
        }
        env.getOut().append(WebUtils.getContextPath() + "/u/" + username + "/post?id=" + id);
    }

}
